package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.sky.constant.MessageConstant.*;
import static com.sky.constant.StatusConstant.DISABLE;


@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    public void add(DishDTO dishDTO) {
        //1.创建菜品Dish对象
        Dish dish = new Dish();
        //2.给Dish对象赋值
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(DISABLE);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //3.调用mapper插入dish对象
        dishMapper.add(dish);
        //4.创建口味list
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //5.给口味list赋值
        if(!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            //6.调用mapper插入list
            dishFlavorMapper.addBatch(flavors);
        }

    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pqgeQuery(DishPageQueryDTO dishPageQueryDTO) {
        //1.开启分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //2.封装page对象
        Page<DishVO> page = dishMapper.pqgeQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 批量删除菜品
     * @param ids
     */
    public void deletBatch(List<Long> ids) {
        //1.判断传入id菜品是否有起售中的
        Integer dishNum = dishMapper.countStartDishNum(ids);
        //1.1若有抛出异常
        if (dishNum > 0){
            throw new DeletionNotAllowedException(DISH_ON_SALE);
        }
        //2.判断传入id是否和套餐相关联
        Integer setMealNum = setmealDishMapper.countSetMealNum(ids);
        //2.2若有抛出异常
        if (setMealNum > 0){
            throw new DeletionNotAllowedException(SETMEAL_ON_SALE);
        }
        //删除菜品
        dishMapper.deletBatch(ids);
        //删除口味
        dishFlavorMapper.deletBatch(ids);
    }

    /**
     * 根据id查询菜品相关信息
     * @param id
     * @return
     */
    public DishVO getById(Long id) {
       /* //1.查询菜品数据
        Dish dish = dishMapper.getById(id);
        //2.查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getById(id);
        //3.封装DishO对象
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);*/
        return dishMapper.getDishVO(id);
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    public void update(DishDTO dishDTO) {
        //1.创建dish对象
        Dish dish = new Dish();
        //2.赋值dish对象
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //3.调用mapper修改菜品表
        dishMapper.update(dish);
        //4.删除口味
        dishFlavorMapper.deletBatch(Arrays.asList(dishDTO.getId()));
        //5.获取口味集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //6.给口味对象赋值
        if (!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }
        //7.调用mapper批量插入口味集合
        dishFlavorMapper.addBatch(flavors);
    }

    /**
     * 起售，停售
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        //1.判断是起售还是停售
        if (status == DISABLE){
            //2.停售的话停售套餐
            //2.1查询菜品相关套餐
            List<Long> setmealIds = setmealDishMapper.getSetMealById(id);
            //2.2如果有 禁用这些套餐
            if (setmealIds != null && setmealIds.size() > 0){
                SetmealMapper.updateStatus(setmealIds,BaseContext.getCurrentId());
            }
        }
        //3.修改菜品状态
        Dish build = Dish.builder().id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        dishMapper.update(build);
    }

    /**
     * 根据分类查询菜品信息
     *
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
       return dishMapper.list(dish);

    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
//        List<Dish> dishList = dishMapper.list(dish);
//
//        List<DishVO> dishVOList = new ArrayList<>();
//
//        for (Dish d : dishList) {
//            DishVO dishVO = new DishVO();
//            BeanUtils.copyProperties(d,dishVO);
//
//            //根据菜品id查询对应的口味
//            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
//
//            dishVO.setFlavors(flavors);
//            dishVOList.add(dishVO);
//        }

        return dishMapper.getDishVOList(dish);
    }
}
